<template>
    <a-drawer :title="title" :width="600" @close="handleCancel(false)" :visible="visible" :maskClosable="false"
              :bodyStyle="{ paddingBottom: '60px' }">

        <a-form-model ref="ruleForm" :model="form" :rules="rules">

            <a-row :gutter="16">

                <a-col :span="24">

                    <a-form-model-item label="标题" prop="title" ref="title">
                        <a-input placeholder="请设置案例标题" v-model="form.title"/>
                    </a-form-model-item>

                </a-col>


                <a-col :span="12">
                    <a-form-model-item label="完工时期" prop="period" ref="period">
                        <a-input placeholder="请设置案例项目的完工时期" v-model="form.period"/>
                    </a-form-model-item>

                </a-col>


                <a-col :span="12">
                    <a-form-model-item label="面积" prop="acreage" ref="acreage">
                        <a-input v-model.number="form.acreage"/>
                    </a-form-model-item>

                </a-col>


                <a-col :span="16" class="sameHeight">

                    <a-form-model-item label="摘要" prop="digest" ref="digest">


                        <a-textarea placeholder="摘要" v-model="form.digest" :rows="5"/>
                    </a-form-model-item>

                </a-col>
                <a-col :span="8" class="sameHeight">


                    <a-form-model-item label="封面图" prop="picture" ref="picture">

                        <a-upload name="file"
                                  list-type="picture-card"
                                  :show-upload-list="false"
                                  :before-upload="beforeUpload"
                                  @change="uploadHandler"
                                  :customRequest="customRequest">
                            <img v-if="form.picture" :src="form.picture" class="PreviewImg"/>
                            <div v-else>
                                <a-icon :type="upLoading ? 'loading' : 'plus'"/>
                                <div class="ant-upload-text">本地上传</div>
                            </div>
                        </a-upload>
                    </a-form-model-item>
                </a-col>


                <a-col :span="16">

                    <a-form-model-item label="详细地址" prop="address" ref="address">
                        <a-input placeholder="详细地址" v-model="form.address"/>
                    </a-form-model-item>

                </a-col>


                <a-col :span="8">

                    <a-form-model-item label="项目坐标" prop="lng" ref="lng">


                        <a-input-search v-model="lngFiled" placeholder="请选择经纬度"
                                        @search="AmapSectorShow=true"
                                        @click="AmapSectorShow=true">

                            <a-button slot="enterButton" type="primary" icon="environment"></a-button>

                        </a-input-search>


                    </a-form-model-item>

                </a-col>


                <a-col :span="24">
                    <a-form-model-item label="图文介绍" prop="content" ref="content">
                        <RichEditor :key="$exMod.randString(10)"
                                    :content="initContent"

                                    :uploadType="'system'"
                                    :height="300"
                                    @editorHandler="(e)=>{form.content=e}"/>

                    </a-form-model-item>
                </a-col>


            </a-row>


        </a-form-model>

        <AmapSector v-if="AmapSectorShow" @closeModal="closeAmapSector" :lnglat="{lng:form.lng,lat:form.lat}"/>

        <!-- Modal 页脚 -->
        <footer class="drawer-footer">
            <a-button type="primary" :loading="loading" @click="onSubmit">保存</a-button>
        </footer>
    </a-drawer>
</template>
<script>

    import {fileUpload} from '../../../util/internal.api'
    import {caseAdd, caseUpdate, caseFind} from '../public/http.js';
    import {formRule} from './validator'


    export default {
        props: ['editRecord'],

        components: {
            AmapSector: () => import('../../../common/AmapSector'),
            RichEditor: () => import('../../../common/RichEditor'),
        },


        data() {
            return {
                upLoading: false,
                isUpdate: false, //是否是更新模式
                loading: false, //按钮Loading
                title: '新增案例',
                visible: true, //modal 显示状态
                initContent:null,
                dataInit:false,
                form: {
                    title: null,
                    period: null,
                    acreage: null,
                    digest: null,
                    picture: null,
                    content: null,
                    province: null,
                    city: null,
                    district: null,
                    address: null,
                    lng: null,
                    lat: null,


                },
                rules: formRule(),

                AmapSectorShow: false,

            };
        },
        methods: {


            //位置选择回调
            closeAmapSector(e) {


                this.AmapSectorShow = false;
                if (e.location) {
                    let {lng, lat, address, province, city, district} = e.location;
                    let ob = {lng, lat, address, province, city, district}
                    //合并对象
                    this.form = Object.assign(this.form, ob)
                    this.$refs.lng.onFieldBlur();
                }


            },


            //表单提交事件
            onSubmit() {
                this.$refs.ruleForm.validate(valid => {
                    //验证成功后进行数据提交
                    if (valid) {
                        this.loading = true;
                        if (this.isUpdate) {
                            caseUpdate(this.form.id, this.form).then(res => {
                                this.$exMod.ajaxMessage(res);
                                if (res.code === 0) {
                                    this.handleCancel(true);
                                }
                            });
                        } else {
                            caseAdd(this.form).then(res => {
                                this.$exMod.ajaxMessage(res);
                                if (res.code === 0) {
                                    this.handleCancel(true);
                                }
                            });
                        }
                    }
                });
            },
            //关闭弹窗 刷新
            handleCancel(render = false) {
                this.visible = false;
                this.$emit('closeFun', {render: render});
            },

            //数据初始化
            async init() {

                let obj = {...this.editRecord};
                if (obj.id) {
                    this.isUpdate = true;
                    this.title = '编辑案例分类';
                await  caseFind(obj.id).then(res => {
                        res.code === 0 ? this.form = res.data.result : null;


                    })
                    this.initContent=this.form.content;

                }
                this.dataInit=true;
            },


            //=============================上传的方法=========================
            customRequest(data) {
                this.upLoading = true;
                const formData = new FormData();
                formData.append('file', data.file);
                fileUpload(formData).then(res => {
                    if (res.code === 0) {
                        this.form.picture = res.data.url
                    } else {
                        this.$exMod.ajaxMessage(res);
                    }

                })
                this.upLoading = false;
            },
            beforeUpload(file) {
                const allowTye = ['bmp', 'png', 'jpeg', 'jpg', 'gif'];
                const fileType = file.type.split("/");
                const checkType = allowTye.findIndex((value, index, arr) => {
                    return value === fileType[1]
                });
                if (checkType < 0) {
                    this.$notification['error']({
                        message: '图片素材添加失败',
                        description: '图片素材只允许上传bmp,png、jpeg、jpg、gif格式的图片'
                    });
                    return false;
                }
                const isLt2M = file.size / 1024 / 1024 < 2;
                if (!isLt2M) {
                    this.$notification['error']({message: '图片素材添加失败', description: "图片素材的大小不能超过 2MB!"});
                    return false;
                }
                return true
            },
            uploadHandler(info) {
                if (info.file.status === 'done') {
                    this.$message.success(`${info.file.name} file uploaded successfully`);
                } else if (info.file.status === 'error') {
                    this.$message.error(`${info.file.name} file upload failed.`);
                }
            },


        },


        computed: {
            lngFiled() {
                if (this.form.lng) {
                    return this.form.lng + ',' + this.form.lat
                } else {
                    return null;
                }

            },
        },
        created() {
            this.init();
        }
    };
</script>
<style scoped>
    .sameHeight {
        height: 170px;
        overflow: hidden;
    }

    .ant-form-item {
        margin-bottom: 0 !important;
    }

    .PreviewImg {
        max-width: 100%;
        max-height: 150px;
        overflow: hidden;
    }
</style>
